import 'dart:convert';

import 'package:data_table_2/data_table_2.dart';
import 'package:flutter/material.dart';
import 'package:shadcn_ui/shadcn_ui.dart';
import 'package:yuellyfactory/views/base/MaterialAddVC.dart';
import 'package:yuellyfactory/views/base/MaterialEditVC.dart';
import 'package:yuellyfactory/views/base/MaterialListVC.dart';

import '../../eventbus/EventBusUtil.dart';
import '../../eventbus/EventRefreshBase.dart';
import '../../util/BaseRequest.dart';
import '../../util/ColorUtil.dart';
import '../../util/MathUtil.dart';
import '../../util/ToastUtil.dart';
import '../../util/ViewUtil.dart';
import '../Controller/MaterialController.dart';
import '../dto/Parameters.dart';
import '../dto/PricePart.dart';
import '../dto/PriceSerial.dart';


class MaterialOldVC extends StatefulWidget {
  final MaterialController partController;
  const MaterialOldVC({super.key, required this.partController});

  @override
  State<MaterialOldVC> createState() => _MaterialOldVCState();
}

class _MaterialOldVCState extends State<MaterialOldVC> {
  final formKey = GlobalKey<ShadFormState>();
  PricePart pricePart=PricePart();
  // Map<String,List<PricePart>> allParts={};
  final dialogKey = GlobalKey<ShadFormState>();

  Map<String,bool> showMaps={};

  List<PriceSerial> serialDatas=[];

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    widget.partController.refreshPricePart=(PricePart part){
      debugPrint('刷新${part.parentId}');
      if(part.parentId !='0'){
        debugPrint('刷新${part.parentId}');
        pricePart=part;
        setState(() {
        });
        getDetail();

      }
    };
  }


  // void checkPricePart(){
  //   Map<String,List<PricePart>> datas={};
  //   for (var item in pricePart.materialList) {
  //     if(item.serialId==null)continue;
  //     if(datas.containsKey(item.serialId)){
  //       datas[item.serialId]?.add(item);
  //     }else{
  //       List<PricePart> list=[];
  //       list.add(item);
  //       datas[item.serialId]=list;
  //     }
  //   }
  //   allParts=datas;
  // }


  void getDetail(){

    var parm={"id":pricePart.id};

    BaseRequest.postHttp("price/branddetail",parameters:parm , canTip: true, context: context, onSuccess: (data){
      bool result=BaseRequest.chekResponse(data, true);
      if(result){
        dynamic datas=data["data"];
        List<PriceSerial> allSerial=[];
        for(var i=0;i<datas.length;i++){
          var item=datas[i];
          var serial=PriceSerial.fromJson(item);
          allSerial.add(serial);
        }
        serialDatas=allSerial;
        setState(() {

        });
      }
    }, onError: (error){

    });
  }

  List<Widget> getAllSerialView(){
    List<Widget> widgets=[];
    // allParts.forEach((key, parts) {
    //   widgets.add(materialView(parts));
    // });

    for(PriceSerial serial in serialDatas){
      widgets.add(materialView(serial));
    }

    return widgets;
  }


  Widget materialView(PriceSerial serial) {

    List<PricePart> list=serial.materialList;
    // 计算表格总高度
    final double tableHeight = _calculateTableHeight(list.length);

    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        const SizedBox(height: 2),
        // 标题和按钮
        Padding(
          padding: EdgeInsets.symmetric(horizontal: _outerPadding),
          child:
          Row(
            crossAxisAlignment: CrossAxisAlignment.baseline,
            textBaseline: TextBaseline.alphabetic,
            children: [
              Text(
                ' ${serial.name}',
                style: TextStyle(fontSize: ViewUtil.fontSize(28)),
              ),
              SizedBox(width: ViewUtil.screenWidth(15),),
              Expanded(child:
              GestureDetector(onTap: (){
                List<Parameters> datas=[];
                datas.add(Parameters("编码", serial.code.toString()));
                datas.add(Parameters("产品系列", serial.productSerial.toString()));
                datas.add(Parameters("适用机型", serial.models.toString()));
                datas.add(Parameters("压缩机", serial.compressor.toString()));
                datas.add(Parameters("定/变频", serial.frequency.toString()));
                datas.add(Parameters("摘要", serial.remark.toString()));
                ViewUtil.showParmSheet(context, '系列参数', datas);
              },child: Text("编码:${serial.code}  产品系列:${serial.productSerial}  适用机型:${serial.models}  压缩机:${serial.compressor}  定/变频:${serial.frequency}  摘要:${serial.remark}",maxLines: 1,overflow: TextOverflow.ellipsis,),)
              ),

              SizedBox(width: ViewUtil.screenWidth(10),),

              IconButton(icon:  Icon( getIsShow(serial.id)?Icons.keyboard_arrow_down_outlined:Icons.keyboard_arrow_right_outlined),
                color:ColorUtil.colorBlue,
                iconSize: ViewUtil.screenWidth(35),onPressed: (){
                  bool result= getIsShow(serial.id);
                  result=!result;
                  showMaps[serial.id]=result;
                  setState(() {

                  });
                },),



              ViewUtil.editIcon('编辑系列',(){
                editSerial(serial);
              }),

              ViewUtil.addIcon('添加型号',(){
                //添加材料
                addMaterial(serial);
              }),
            ],
          ),
        ),
        const SizedBox(height: 10),

        Visibility(
            visible: getIsShow(serial.id),
            child: Column(
              children: [
                Padding(
                  padding: EdgeInsets.symmetric(horizontal: _outerPadding),
                  child: Container(
                    // 应用计算出的高度
                    height: tableHeight,
                    decoration: BoxDecoration(
                      border: Border.all(color: Colors.grey[200]!, width: _borderWidth),
                      borderRadius: BorderRadius.circular(8),
                    ),
                    child: DataTable2(
                      columnSpacing: 12,
                      //  minWidth: MediaQuery.of(context).size.width - 2 * _outerPadding,
                      minWidth: 1500,
                      headingRowHeight: _headerHeight - 2 * _borderWidth, // 减去边框占用高度
                      dataRowHeight: _rowHeight - 2 * _borderWidth, // 减去边框占用高度
                      // 表头
                      columns: const [
                        DataColumn2(
                          label: Text('操作'),
                          fixedWidth: 150,
                        ),
                        DataColumn2(
                          label: Text('Code'),
                          fixedWidth: 150,
                        ),
                        DataColumn2(
                          label: Text('型号名称'),
                          fixedWidth: 150,
                        ),
                        DataColumn2(
                          label: Text('单价'),
                          fixedWidth: 100,
                        ),
                        DataColumn2(
                          label: Text('规格'),
                          fixedWidth: 600,
                        ),
                      ],

                      // 表格内容（行高固定）
                      rows: list.map((item) {
                        return DataRow(cells: [
                          DataCell(Row(children: [
                            ViewUtil.textButton('零件', ViewUtil.screenWidth(20), ViewUtil.screenHeight(10), ViewUtil.radio(15),
                                ColorUtil.colorBlue, ColorUtil.colorBlue, Colors.white , ViewUtil.fontSize(22), (){
                                  showShadSheet(
                                    side: ShadSheetSide.right,
                                    context: context,
                                    builder: (context) =>
                                        MaterialListVC(pricePart:item , callback: () {
                                          //回调
                                        },),
                                  );


                                }),
                            const SizedBox(width: 10,),
                            ViewUtil.editIcon('编辑零件',(){editMaterial(item,serial);}),
                          ],)),
                          DataCell(Padding(
                            padding: const EdgeInsets.symmetric(vertical: 12),
                            child: Text(item.code),
                          )),
                          DataCell(Padding(
                            padding: const EdgeInsets.symmetric(vertical: 12),
                            child: Text(item.name),
                          )),


                          DataCell(Padding(
                            padding: const EdgeInsets.symmetric(vertical: 12),
                            child: Text(MathUtil.formatDouble(item.dPrice, 2)),
                          )),

                          DataCell(
                              GestureDetector(onTap: (){
                                List<Parameters> datas=[];
                                datas.add(Parameters("型号名称", item.name));
                                datas.add(Parameters("Code", item.code));
                                var spec=item.spec;
                                if(spec.isNotEmpty){
                                  var  specsList=jsonDecode(spec);
                                  for(var item in specsList){
                                    datas.add(Parameters(item["name"],item["value"]));
                                  }
                                }
                                ViewUtil.showParmSheet(context, '规格参数', datas);
                              },child: Padding(
                                padding: const EdgeInsets.symmetric(vertical: 12),
                                child: Text(getPartSpec(item)),
                              ),)
                          ),

                        ]);
                      }).toList(),
                    ),
                  ),
                ),
                const SizedBox(height: 20),
              ],
            )),
        // 表格（高度固定为计算值）

      ],
    );
  }


  getPartSpec(PricePart partData){
    var spec=partData.spec;
    var value="";
    if(spec.isNotEmpty){
      var  specsList=jsonDecode(spec);
      for(var item in specsList){
        var str="${item["name"]}:${item["value"]}";
        value="$value$str | ";
      }
    }

    return value;
  }
  // 固定高度参数（可根据需求调整）
  final double _headerHeight = 56; // 表头高度（含内边距）
  final double _rowHeight = 48; // 每行高度（含内边距）
  final double _borderWidth = 1; // 边框宽度
  final double _outerPadding = 10; // 表格外间距

  // 计算表格总高度的核心方法
  double _calculateTableHeight(int length) {
    // 总高度 = 表头高度 + 数据行总高度 + 边框总高度
    // 边框高度：上下边框（2条）+ 行之间的分隔线（数据行数-1条）
    final int borderCount = 2 + (length - 1);
    final double totalBorderHeight = borderCount * _borderWidth;

    return _headerHeight + // 表头高度
        (_rowHeight * length) + // 所有数据行高度
        totalBorderHeight; // 边框总高度
  }


  @override
  void dispose() {

    super.dispose();
  }


  @override
  Widget build(BuildContext context) {
    return Column(

      children: [

        Row(
          children: [
            Text('品牌名称 : ${pricePart.name}',style: TextStyle(fontSize: ViewUtil.fontSize(28),fontWeight: FontWeight.bold),),
            SizedBox(width: ViewUtil.screenWidth(20),),
            Expanded(child: Container()),
            ViewUtil.iconButton(Icons.note_alt_outlined, ColorUtil.colorBlue,  ViewUtil.screenWidth(35), (){

              editBrand();
            }),

            ViewUtil.iconButton(Icons.add_circle_outline, ColorUtil.colorBlue, ViewUtil.screenWidth(35), (){
              editSerial(PriceSerial());
            }),
            SizedBox(width: 10,),

          ],
        ),

        // ViewUtil.lineView(),
        // const SizedBox(height: 10),
        // Row(
        //   children: [
        //
        //     Text('系列',style: TextStyle(fontSize: ViewUtil.fontSize(28)),),
        //     Expanded(child: Container()),
        //     ViewUtil.iconButton(Icons.add_circle_outline, ColorUtil.colorBlue, ViewUtil.screenWidth(35), (){
        //       editSerial(PriceSerial());
        //     })
        //
        //
        //   ],
        // ),

        // const SizedBox(height: 16),
        //    Row(
        //       children: [
        //
        //         Text('型号',style: TextStyle(fontSize: ViewUtil.fontSize(28)),),
        //         SizedBox(width: ViewUtil.screenWidth(10),),
        //         ViewUtil.textButton('新增型号', 20, 15, ViewUtil.radio(15),
        //             ColorUtil.colorBlue, ColorUtil.colorBlue, Colors.white , ViewUtil.fontSize(20), (){
        //
        //               addMaterial();
        //         }),
        //
        //       ],
        //     ),


        Column(children: getAllSerialView(),)

      ],
    );
  }
  void editBrand(){
    showShadDialog(context: context, builder: (context)=>
        ShadDialog(
            actions: [ShadButton(child: Text('确定'),onPressed: (){
              submitPart();
            },)],
            child:
            ShadForm(
              key: formKey,
              child: ShadInputFormField(
                id: 'name',
                label: const Text('品牌名称'),
                placeholder: const Text('请输入品牌名称'),
                initialValue: pricePart.name,
                validator: (v) {
                  if (v.isEmpty) {
                    return '请输入品牌名称';
                  }
                  return null;
                },
              ),)

        )
    );
  }

  void submitPart(){
    if (formKey.currentState!.saveAndValidate()) {
      var values= formKey.currentState!.value;
      var name=values["name"];
      var parm={
        "name":name,
        "id":pricePart.id,
      };
      BaseRequest.postHttp("price/editpart",parameters: parm, canTip: true, context: context, onSuccess: (data){
        bool result=BaseRequest.chekResponse(data, true);
        if(result){
          ToastUtil.showToast("保存成功");
          eventBus.fire(EventRefreshBase());
          Navigator.pop(context);
        }
      }, onError: (error){

      });
    }
  }

  void addMaterial(PriceSerial serial){
    showShadSheet(
      side: ShadSheetSide.right,
      context: context,
      builder: (context) =>  MaterialAddVC(pricePart:pricePart , callback: () {
        //回调
        getDetail();
      },),
    );
  }

  void editMaterial(PricePart priceData,PriceSerial serial){
    showShadSheet(
      side: ShadSheetSide.right,
      context: context,
      builder: (context) =>  MaterialEditVC(pricePart:priceData , callback: () {
        //回调
      },),
    );
  }









  void editSerial(PriceSerial serial){
    final frequency=["定频","变频"];

    List<String> fSelect=[];
    if(serial.frequency.contains("定频")){
      fSelect.add("定频");
    }
    if(serial.frequency.contains("变频")){
      fSelect.add("变频");
    }

    showShadDialog(context: context, builder: (context)=>
        ShadDialog(

            actions: [ShadButton(child: Text('确定'),onPressed: (){
              submitSerial(serial);
            },)],
            child:
            ShadForm(
              key: dialogKey,
              child:
              Column(
                children: [
                  ShadInputFormField(
                    id: 'name',
                    initialValue: serial.name,
                    label: const Text('系列名称'),
                    placeholder: const Text('请输入系列名称'),
                    validator: (v) {
                      if (v.isEmpty) {
                        return '请输入系列名称';
                      }
                      return null;
                    },
                  ),
                  ShadInputFormField(
                    id: 'code',
                    initialValue: serial.code,
                    label: const Text('部件编码'),
                    placeholder: const Text('请输入部件编码'),
                    validator: (v) {
                      if (v.isEmpty) {
                        return '请输入部件编码';
                      }
                      return null;
                    },
                  ),
                  ShadInputFormField(
                    id: 'productSerial',
                    initialValue: serial.productSerial,
                    label: const Text('适用产品系列'),
                    placeholder: const Text('适用产品系列'),
                    validator: (v) {
                      if (v.isEmpty) {
                        return '请输入产品系列';
                      }
                      return null;
                    },
                  ),
                  ShadInputFormField(
                    id: 'models',
                    initialValue: serial.models,
                    label: const Text('适用机型'),
                    placeholder: const Text('适用机型'),
                    validator: (v) {
                      if (v.isEmpty) {
                        return '请输入适用机型';
                      }
                      return null;
                    },
                  ),
                  ShadInputFormField(
                    id: 'compressor',
                    initialValue: serial.compressor,
                    label: const Text('压缩机'),
                    placeholder: const Text('请输入压缩机'),

                  ),



                  ShadSelectMultipleFormField<String>(
                    id: 'frequency',
                    minWidth: 480,
                    maxWidth: 480,
                    label: const Text('定/变频'),
                    initialValue: fSelect,
                    options: frequency
                        .map((item) => ShadOption(value: item, child: Text(item)))
                        .toList(),

                    placeholder: const Text('请选择'),

                    validator: (v) {
                      if (v == null||v.isEmpty) {
                        return '请选择';
                      }
                      return null;
                    },
                    selectedOptionsBuilder: (context, values) =>
                        Text(values.map((v) => v).join(', ')),


                  ),


                  ShadInputFormField(
                    id: 'remark',
                    initialValue: serial.remark,
                    label: const Text('摘要'),
                    placeholder: const Text('请输入摘要'),

                  ),
                ],
              ),)

        )
    );
  }

  void submitSerial(PriceSerial serial){
    if (dialogKey.currentState!.saveAndValidate()) {
      var values= dialogKey.currentState!.value;
      var name=values["name"];
      var code=values["code"];
      var productSerial=values["productSerial"];
      var models=values["models"];
      var compressor=values["compressor"];
      var frequency=values["frequency"];
      var remark=values["remark"];
      var fSelect=frequency.map((v) => v).join(', ');

      var parm={
        "name":name,
        "id":serial.id,
        "partId":pricePart.id,
        "code":code,
        "productSerial":productSerial,
        "models":models,
        "compressor":compressor,
        "frequency":fSelect,
        "remark":remark

      };
      BaseRequest.postHttp("price/editpartserial",parameters: parm, canTip: true, context: context, onSuccess: (data){
        bool result=BaseRequest.chekResponse(data, true);
        if(result){
          ToastUtil.showToast("编辑成功");
          eventBus.fire(EventRefreshBase());
          Navigator.pop(context);

        }
      }, onError: (error){

      });
    }
  }

  getIsShow(String id){
    bool result=false;
    if(showMaps.containsKey(id)){
      return showMaps[id];
    }
    return result;
  }



}
